package com.by_man.presenter.menu_activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.by_man.presenter.R;
import com.by_man.presenter.SharedApplication;
import com.by_man.presenter.main_page.MainActivity;
import com.by_man.repository.LocalDataManager;
import com.by_man.repository.UserInfos;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by man on 2017-03-09.
 */
public class PublicNumberActivity extends AppCompatActivity {
    private TextView contentView;
    private ImageView imageView;
    private Handler handler;
    private ProgressDialog progressDialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_public_number);
        //页面相关组件的初始化
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                Bundle bundl = msg.getData();
                Bitmap bitmap = (Bitmap) bundl.get("Bitmap");
                if (null != bitmap) {
                    imageView.setImageBitmap(bitmap);
                } else {
                    initView();
                }
            }
        };
        dataInitWait();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
//                Intent intent = new Intent(this, MainActivity.class);
//                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                startActivity(intent);
                onBackPressed();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            Intent intent = new Intent(this, MainActivity.class);
//            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//            startActivity(intent);
//        }
//        return super.onKeyDown(keyCode,event);
//    }

    private void initView() {
        // 初始化ToolBar
        Toolbar toolbar = (Toolbar)findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setHomeAsUpIndicator(R.drawable.icon_back);
        actionBar.setDisplayHomeAsUpEnabled(true);

        JSONArray jsonArray = UserInfos.Public_Number;
        if (null != jsonArray && jsonArray.length() != 0) {
            try {
                String path;
                String content;
                JSONObject temp;
                temp = (JSONObject) jsonArray.get(0);
                content = temp.getString("content");
                path = temp.getString("path");
                contentView.setText(content);
                ImageRequest imageRequest = new ImageRequest(path,
                        new Response.Listener<Bitmap>() {
                            @Override
                            public void onResponse(Bitmap bitmap) {
                                if (null != bitmap) {
                                    Message msg = handler.obtainMessage();
                                    Bundle bundle = new Bundle();
                                    bundle.putParcelable("Bitmap", bitmap);
                                    msg.setData(bundle);
                                    msg.sendToTarget();
                                }
                            }
                        }, 0, 0, Bitmap.Config.RGB_565,
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError volleyError) {
                                Log.e("PublicNumberError", volleyError.getMessage(),volleyError);
                            }
                        });
                LocalDataManager.getRequestQueue().add(imageRequest);
            } catch (JSONException je) {
                je.printStackTrace();
            }
        }


    }

    private void dataInitWait() {
        if (null == UserInfos.Public_Number) {     // 没有数据
            progressDialog = new ProgressDialog(this);
            progressDialog.setTitle("提示信息");
            progressDialog.setMessage("正在请求数据，请稍后......");
            progressDialog.setCancelable(false);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.show();

            Thread thread = new Thread() {
                public void run() {
                    while (null == UserInfos.Public_Number) {  // 阻塞等待数据的初始化

                    }
                    progressDialog.dismiss();
                    Message message = Message.obtain(handler);
                    message.sendToTarget();
                }
            };
            thread.setDaemon(true);             // 设置为守护线程
            thread.start();
        } else {
            initView();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }
}
